<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import type { ComponentSize, FormInstance, FormRules, UploadInstance, UploadFile } from 'element-plus';
import { ElMessageBox, ElMessage } from 'element-plus';
import axios from 'axios';
import NavMenu from './component/NavMenu.vue';

// 表单数据类型
interface RuleForm {
    webUrl: string;
    userId: string;
    phishing: string;
}

// 表格数据类型
interface DataSet {
    updateTime: string;
    webUrl: string;
    userId: string;
    phishing: string;
    webId: string;
}

// 表单大小
const formSize = ref<ComponentSize>('default');

// 表单引用
const ruleFormRef = ref<FormInstance>();

// 表单数据
const ruleForm = reactive<RuleForm>({
    webUrl: '',
    userId: '',
    phishing: ''
});

// 表单验证规则
const rules = reactive<FormRules<RuleForm>>({
    webUrl: [
        { required: true, message: '请输入网站URL', trigger: 'blur' },
    ],
    phishing: [
        { required: true, message: '请选择是否为钓鱼网站', trigger: 'change' },
    ],
});

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    try {
        await formEl.validate((valid) => {
            if (valid) {
                console.log('表单提交成功:', ruleForm);
                // 构造要发送的数据
                const webData = {
                    webUrl: ruleForm.webUrl,
                    userId: ruleForm.userId,
                    phishing: ruleForm.phishing
                };
                // 发送 POST 请求
                axios.post('http://127.0.0.1:8080/addWeb', webData)
                    .then(async (response) => {
                        if (response.data.code === 1) {
                            ElMessage.success('提交成功！');
                            dialogVisible.value = false; // 关闭对话框
                            const response = await axios.get('http://127.0.0.1:8080/allWeb');
                            tableData.value = response.data.data;
                            resetForm(ruleFormRef.value);
                        } else {
                            ElMessage.error('提交失败：' + response.data.message);
                        }
                    })
                    .catch((error) => {
                        console.error('提交失败:', error);
                        ElMessage.error('提交失败，请重试！');
                    });
            } else {
                console.log('表单验证失败');
                ElMessage.error('请填写完整信息！');
            }
        });
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败，请重试！');
    }
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

// 表格数据
const tableData = ref<DataSet[]>([]);
const stored_user = localStorage.getItem("user_information");
const user_info = JSON.parse(stored_user || '{}');

// 页面加载时获取数据
onMounted(async () => {
    ruleForm.userId = user_info.uid;
    console.log(user_info.uid)
    try {
        const response = await axios.get('http://127.0.0.1:8080/allWeb');
        if (response.data.code === 1) {
            tableData.value = response.data.data;
        } else {
            ElMessage.error('数据加载失败');
        }
    } catch (error) {
        console.error('数据加载失败:', error);
        ElMessage.error('数据加载失败，请重试');
    }
});

// 表格搜索功能
const search = ref('');
const filterTableData = computed(() =>
    tableData.value.filter(
        (data) =>
            !search.value ||
            data.webId.toLowerCase().includes(search.value.toLowerCase())
    ));

// 表格操作
const handleEdit = (index: number, row: DataSet) => {
    console.log('编辑行:', index, row);
};

// 查询表单
const formInline = reactive({
    webId: '',
    user: '',
    date: '',
    datestart: '',
    dateend: ''
});

const onSubmit = async () => {
    if (formInline.date !== '') {
        let dates = formInline.date[0];
        let datee = formInline.date[1];
        let date = new Date(dates);
        let formattedDate = date.getFullYear() + '-' +
            ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
            ('0' + date.getDate()).slice(-2);
        formInline.datestart = formattedDate;
        date = new Date(datee);
        formattedDate = date.getFullYear() + '-' +
            ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
            ('0' + date.getDate()).slice(-2);
        formInline.dateend = formattedDate;
    }
    console.log(formInline.datestart, ' ', formInline.dateend);

    try {
        const response = await axios.post('http://127.0.0.1:8080/selectWeb', {
            webId: formInline.webId,
            userId: formInline.user,
            updateTimeStart: formInline.datestart,
            updateTimeEnd: formInline.dateend
        });

        if (response.data.msg === "success") {
            console.log('查询成功:', response.data);
            ElMessage.success('查询成功');
            tableData.value = response.data.data;
        } else {
            console.error('查询失败');
            ElMessage.error('查询失败');
        }
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('查询失败');
    }
};

// 对话框逻辑
const dialogVisible = ref(false);
const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确定关闭对话框吗？')
        .then(() => {
            resetForm(ruleFormRef.value);
            done();
        })
        .catch(() => {
            // 取消关闭
        });
};

// 格式化时间
const formatUpdateTime = (row: DataSet, column: any, cellValue: string) => {
    return cellValue.replace('T', ' ').split('+')[0];
};

// 分页
const currentPage = ref(1);
const pageSize = ref(5);
const size = ref<ComponentSize>('default');
const background = ref(false);
const disabled = ref(false);

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
};
</script>

<template>
    <div>
        <NavMenu />
        <el-container>
            <el-main>
                <!-- 搜索表单 -->
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="网站ID">
                        <el-input v-model="formInline.webId" placeholder="网站ID" style="width:170px" clearable />
                    </el-form-item>
                    <el-form-item label="上传用户">
                        <el-input v-model="formInline.user" placeholder="上传用户id" style="width:170px" clearable />
                    </el-form-item>
                    <el-form-item label="上传日期">
                        <el-date-picker v-model="formInline.date" type="daterange" unlink-panels range-separator="到"
                            start-placeholder="开始日期" end-placeholder="结束日期" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>
                        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>
                    </el-form-item>
                </el-form>

                <!-- 数据表格 -->
                <el-table :data="filterTableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                    style="width: 100%">
                    <el-table-column label="网站ID" prop="webId" />
                    <el-table-column label="上传用户" prop="userId" />
                    <el-table-column label="网站URL">
                        <template #default="scope">
                            <el-link :href="scope.row.webUrl" target="_blank" :underline="false">{{
                                scope.row.webUrl }}</el-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否为钓鱼网站" prop="phishing">
                        <template #default="scope">
                            <span v-if="scope.row.phishing === '0'">否</span>
                            <span v-else-if="scope.row.phishing === '1'">是</span>
                            <span v-else-if="scope.row.phishing === '2'">疑似</span>
                            <span v-else>未知</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="上传日期" prop="updateTime" :formatter="formatUpdateTime" />
                    <el-table-column align="right">
                        <template #header>
                            <el-input v-model="search" size="small" placeholder="Type to search" />
                        </template>
                        <template #default="scope">
                            <el-button size="small" v-if="scope.row.userId === user_info.userId"
                                @click="handleEdit(scope.$index, scope.row)">
                                编辑
                            </el-button>
                            <el-button size="small" v-else disabled>
                                编辑
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="demo-pagination-block">
                    <div class="demonstration"></div>
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[1, 5, 10, 20]" :size="size" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="filterTableData.length"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </el-main>

            <!-- 新增网站对话框 -->
            <el-dialog v-model="dialogVisible" title="新增网站" width="500" :before-close="handleClose">
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
                    :size="formSize" status-icon>
                    <!-- 网站URL -->
                    <el-form-item label="网站URL" prop="webUrl">
                        <el-input v-model="ruleForm.webUrl" placeholder="请输入网站URL" />
                    </el-form-item>
                    <!-- 钓鱼网站标识 -->
                    <el-form-item label="钓鱼网站" prop="phishing">
                        <el-select v-model="ruleForm.phishing" placeholder="请选择">
                            <el-option label="是" value="1" />
                            <el-option label="否" value="0" />
                            <el-option label="疑似" value="2" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-container>
    </div>
</template>

<style>
.demo-form-inline .el-input {
    --el-input-width: 150px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}
</style>